<template>
  <div class="discount-modal-wrapper" v-if="visible" @click.self="handleCancel">
    <div class="discount-modal">
      <!-- 标题栏 -->
      <div class="modal-header">
        <h2 class="modal-title">设置折扣价格</h2>
        <button class="close-button" @click="handleCancel">×</button>
      </div>
      
      <!-- 商品信息区域 -->
      <div class="product-info">
        <div class="product-image">
          <img :src="product.image" :alt="product.name" />
        </div>
        <div class="product-details">
          <h3 class="product-name">{{ product.name }}</h3>
          <div class="product-restaurant">{{ product.restaurant?.name }}</div>
          <div class="product-price">原价: {{ formatPrice(product.price) }} USDT</div>
        </div>
      </div>
      
      <!-- 折扣价格设置区域 -->
      <div class="discount-setting">
        <h4 class="section-title">折扣价格设置</h4>
        
        <div class="price-input-group">
          <div class="input-label">折扣价格 (USDT)</div>
          <input 
            type="number" 
            v-model="discountPrice" 
            class="price-input" 
            :class="{ 'has-error': priceError }"
            @input="handlePriceInput"
            step="0.1"
            min="0"
          />
        </div>
        
        <!-- 价格错误提示 -->
        <div class="error-message" v-if="priceError">{{ priceError }}</div>
        
        <!-- 价格滑动条 -->
        <div class="price-slider-container">
          <div class="slider-labels">
            <span class="min-price">最低: {{ formatPrice(minPrice) }} USDT</span>
            <span class="max-price">原价: {{ formatPrice(product.price) }} USDT</span>
          </div>
          <input 
            type="range" 
            v-model="sliderValue" 
            class="price-slider" 
            :min="minPrice" 
            :max="product.price" 
            :step="0.1"
            @input="handleSliderInput"
          />
          
          <!-- 折扣百分比 -->
          <div class="discount-percentage">
            <span class="discount-label">折扣:</span>
            <span class="discount-value" :class="getDiscountClass()">{{ discountPercentage }}% OFF</span>
          </div>
        </div>
      </div>
      
      <!-- 佣金计算预览 -->
      <div class="commission-preview">
        <h4 class="section-title">佣金预览</h4>
        <div class="commission-calculation">
          <div class="commission-formula">
            <span class="formula-label">计算公式:</span>
            <span class="formula-value">(原价 - 折扣价) × {{ commissionRate * 100 }}%</span>
          </div>
          <div class="commission-result">
            <span class="result-label">预计佣金:</span>
            <span class="result-value">{{ formatPrice(calculatedCommission) }} USDT</span>
          </div>
        </div>
        
        <!-- 佣金说明 -->
        <div class="commission-note">
          <div class="note-icon">i</div>
          <div class="note-text">
            佣金将在订单完成后自动计入您的账户，可在佣金管理页面查看详情
          </div>
        </div>
      </div>
      
      <!-- 个性化名称设置 -->
      <div class="custom-name-setting">
        <h4 class="section-title">设置个性化名称</h4>
        <div class="name-input-container">
          <input 
            type="text" 
            v-model="customName" 
            class="name-input"
            :class="{ 'has-error': nameError }"
            placeholder="请输入您的名称"
            maxlength="20"
          />
          <div class="remaining-chars">{{ 20 - customName.length }}</div>
        </div>
        
        <!-- 名称错误提示 -->
        <div class="error-message" v-if="nameError">{{ nameError }}</div>
        
        <!-- 名称说明 -->
        <div class="name-preview">
          <span class="preview-label">支付页面将显示:</span>
          <span class="preview-text">"您正在帮助 <strong>{{ customName || '您' }}</strong> 支付外卖"</span>
        </div>
      </div>
      
      <!-- 按钮区域 -->
      <div class="modal-footer">
        <button class="cancel-button" @click="handleCancel">取消</button>
        <button 
          class="confirm-button" 
          :disabled="!isFormValid || isGenerating"
          @click="handleConfirm"
        >
          <span v-if="isGenerating" class="loading-spinner"></span>
          <span>{{ isGenerating ? '生成中...' : '生成支付链接' }}</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, defineProps, defineEmits } from 'vue';

interface Product {
  id: string | number;
  name: string;
  price: number;
  image: string;
  restaurant?: {
    name: string;
  };
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  product: {
    type: Object as () => Product,
    required: true,
    default: () => ({
      id: '',
      name: '',
      price: 0,
      image: '',
      restaurant: { name: '' }
    })
  },
  commissionRate: {
    type: Number,
    default: 0.15 // 默认佣金率15%
  },
  minDiscountPercentage: {
    type: Number,
    default: 5 // 最小折扣5%
  }
});

const emit = defineEmits([
  'cancel',                   // 取消操作
  'confirm',                  // 确认生成链接
  'update:visible'            // 更新可见状态
]);

// 计算最低价格（根据最小折扣百分比）
const minPrice = computed(() => {
  return props.product.price * (1 - props.minDiscountPercentage / 100);
});

// 状态变量
const discountPrice = ref(props.product.price * 0.9); // 默认九折
const sliderValue = ref(props.product.price * 0.9);
const customName = ref('');
const priceError = ref('');
const nameError = ref('');
const isGenerating = ref(false);

// 计算折扣百分比
const discountPercentage = computed(() => {
  const percentage = Math.round((1 - discountPrice.value / props.product.price) * 100);
  return percentage > 0 ? percentage : 0;
});

// 计算佣金金额
const calculatedCommission = computed(() => {
  if (discountPrice.value >= props.product.price) {
    return 0;
  }
  return (props.product.price - discountPrice.value) * props.commissionRate;
});

// 表单验证
const isFormValid = computed(() => {
  return !priceError.value 
    && !nameError.value 
    && discountPrice.value > 0 
    && discountPrice.value < props.product.price;
});

// 格式化价格显示
const formatPrice = (price: number): string => {
  return price.toFixed(2);
};

// 获取折扣级别的CSS类
const getDiscountClass = () => {
  const discount = discountPercentage.value;
  if (discount >= 30) return 'discount-high';
  if (discount >= 15) return 'discount-medium';
  return 'discount-low';
};

// 处理价格输入
const handlePriceInput = () => {
  // 验证输入的价格
  if (discountPrice.value <= 0) {
    priceError.value = '折扣价格必须大于0';
  } else if (discountPrice.value >= props.product.price) {
    priceError.value = '折扣价格必须低于原价';
  } else if (discountPrice.value < minPrice.value) {
    priceError.value = `折扣价格不能低于最低价格 ${formatPrice(minPrice.value)} USDT`;
  } else {
    priceError.value = '';
  }
  
  // 更新滑动条值
  sliderValue.value = Number(discountPrice.value);
};

// 处理滑动条输入
const handleSliderInput = () => {
  // 更新价格输入框
  discountPrice.value = Number(sliderValue.value);
  
  // 验证输入的价格
  if (discountPrice.value <= 0) {
    priceError.value = '折扣价格必须大于0';
  } else if (discountPrice.value >= props.product.price) {
    priceError.value = '折扣价格必须低于原价';
  } else if (discountPrice.value < minPrice.value) {
    priceError.value = `折扣价格不能低于最低价格 ${formatPrice(minPrice.value)} USDT`;
  } else {
    priceError.value = '';
  }
};

// 监听customName变化进行验证
watch(customName, (newValue) => {
  if (newValue.length > 20) {
    nameError.value = '名称不能超过20个字符';
  } else {
    nameError.value = '';
  }
});

// 取消按钮点击处理
const handleCancel = () => {
  emit('update:visible', false);
  emit('cancel');
};

// 确认按钮点击处理
const handleConfirm = () => {
  // 最终验证
  if (!isFormValid.value) {
    return;
  }
  
  // 显示加载状态
  isGenerating.value = true;
  
  // 准备数据
  const discountData = {
    productId: props.product.id,
    originalPrice: props.product.price,
    discountPrice: discountPrice.value,
    discountPercentage: discountPercentage.value,
    commissionAmount: calculatedCommission.value,
    customName: customName.value.trim() || '您'
  };
  
  // 模拟API请求延迟
  setTimeout(() => {
    // 发送确认事件
    emit('confirm', discountData);
    
    // 重置状态
    isGenerating.value = false;
    
    // 关闭模态框
    emit('update:visible', false);
  }, 800);
};
</script>

<style lang="scss" scoped>
.discount-modal-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  overflow-y: auto;
  padding: 20px;
}

.discount-modal {
  width: 100%;
  max-width: 480px;
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  
  .modal-title {
    font-size: 18px;
    font-weight: 600;
    color: #2F3542;
    margin: 0;
  }
  
  .close-button {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    border: none;
    background-color: #f5f5f5;
    color: #666;
    font-size: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s ease;
    
    &:hover {
      background-color: #e0e0e0;
      color: #333;
    }
  }
}

.product-info {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #f5f5f5;
  
  .product-image {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    overflow: hidden;
    flex-shrink: 0;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  .product-details {
    margin-left: 16px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    
    .product-name {
      font-size: 16px;
      font-weight: 600;
      color: #2F3542;
      margin: 0 0 4px 0;
    }
    
    .product-restaurant {
      font-size: 14px;
      color: #6C757D;
      margin-bottom: 8px;
    }
    
    .product-price {
      font-size: 15px;
      font-weight: 500;
      color: #2F3542;
    }
  }
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #2F3542;
  margin: 0 0 12px 0;
}

.discount-setting {
  padding: 20px;
  border-bottom: 1px solid #f5f5f5;
  
  .price-input-group {
    margin-bottom: 8px;
    
    .input-label {
      font-size: 14px;
      color: #6C757D;
      margin-bottom: 8px;
    }
    
    .price-input {
      width: 100%;
      height: 44px;
      padding: 0 16px;
      border: 1px solid #ddd;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 500;
      color: #2F3542;
      
      &:focus {
        border-color: #FF4757;
        outline: none;
        box-shadow: 0 0 0 2px rgba(255, 71, 87, 0.2);
      }
      
      &.has-error {
        border-color: #DC3545;
      }
    }
  }
  
  .error-message {
    color: #DC3545;
    font-size: 12px;
    margin-bottom: 12px;
  }
  
  .price-slider-container {
    margin-top: 16px;
    
    .slider-labels {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
      
      .min-price, .max-price {
        font-size: 13px;
        color: #6C757D;
      }
    }
    
    .price-slider {
      width: 100%;
      height: 6px;
      appearance: none;
      background: linear-gradient(to right, #FF4757, #FFA502);
      border-radius: 3px;
      outline: none;
      
      &::-webkit-slider-thumb {
        appearance: none;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background: #FF4757;
        cursor: pointer;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        transition: transform 0.1s ease;
        
        &:active {
          transform: scale(1.2);
        }
      }
      
      &::-moz-range-thumb {
        width: 20px;
        height: 20px;
        border: none;
        border-radius: 50%;
        background: #FF4757;
        cursor: pointer;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        transition: transform 0.1s ease;
        
        &:active {
          transform: scale(1.2);
        }
      }
    }
    
    .discount-percentage {
      display: flex;
      align-items: center;
      margin-top: 12px;
      
      .discount-label {
        font-size: 14px;
        color: #6C757D;
      }
      
      .discount-value {
        font-size: 14px;
        font-weight: 600;
        margin-left: 8px;
        padding: 2px 8px;
        border-radius: 4px;
        
        &.discount-low {
          background-color: rgba(255, 193, 7, 0.15);
          color: #FF9800;
        }
        
        &.discount-medium {
          background-color: rgba(255, 87, 36, 0.15);
          color: #FF5722;
        }
        
        &.discount-high {
          background-color: rgba(255, 71, 87, 0.15);
          color: #FF4757;
        }
      }
    }
  }
}

.commission-preview {
  padding: 20px;
  border-bottom: 1px solid #f5f5f5;
  
  .commission-calculation {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;
    
    .commission-formula, .commission-result {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .formula-label, .result-label {
        font-size: 14px;
        color: #6C757D;
      }
      
      .formula-value {
        font-size: 14px;
        color: #2F3542;
      }
      
      .result-value {
        font-size: 18px;
        font-weight: 600;
        color: #28A745;
      }
    }
    
    .commission-result {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px dashed #ddd;
    }
  }
  
  .commission-note {
    display: flex;
    align-items: flex-start;
    
    .note-icon {
      width: 18px;
      height: 18px;
      border-radius: 50%;
      background-color: #6C757D;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 11px;
      font-weight: 600;
      flex-shrink: 0;
      margin-top: 2px;
    }
    
    .note-text {
      font-size: 13px;
      color: #6C757D;
      line-height: 1.5;
      margin-left: 8px;
    }
  }
}

.custom-name-setting {
  padding: 20px;
  border-bottom: 1px solid #f5f5f5;
  
  .name-input-container {
    position: relative;
    margin-bottom: 8px;
    
    .name-input {
      width: 100%;
      height: 44px;
      padding: 0 40px 0 16px;
      border: 1px solid #ddd;
      border-radius: 8px;
      font-size: 15px;
      color: #2F3542;
      
      &:focus {
        border-color: #FF4757;
        outline: none;
        box-shadow: 0 0 0 2px rgba(255, 71, 87, 0.2);
      }
      
      &.has-error {
        border-color: #DC3545;
      }
      
      &::placeholder {
        color: #ADB5BD;
      }
    }
    
    .remaining-chars {
      position: absolute;
      right: 12px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 12px;
      color: #ADB5BD;
    }
  }
  
  .error-message {
    color: #DC3545;
    font-size: 12px;
    margin-bottom: 12px;
  }
  
  .name-preview {
    font-size: 13px;
    color: #6C757D;
    
    .preview-label {
      margin-right: 4px;
    }
    
    .preview-text {
      color: #2F3542;
      
      strong {
        color: #FF4757;
      }
    }
  }
}

.modal-footer {
  padding: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  
  .cancel-button, .confirm-button {
    height: 44px;
    padding: 0 20px;
    border-radius: 8px;
    font-size: 15px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .cancel-button {
    background-color: #f5f5f5;
    color: #6C757D;
    border: none;
    
    &:hover {
      background-color: #e0e0e0;
      color: #2F3542;
    }
  }
  
  .confirm-button {
    background-color: #FF4757;
    color: white;
    border: none;
    min-width: 160px;
    
    &:hover {
      background-color: darken(#FF4757, 8%);
      transform: translateY(-2px);
      box-shadow: 0 4px 10px rgba(255, 71, 87, 0.3);
    }
    
    &:disabled {
      background-color: #f5f5f5;
      color: #ADB5BD;
      cursor: not-allowed;
      transform: none;
      box-shadow: none;
    }
    
    .loading-spinner {
      width: 16px;
      height: 16px;
      border: 2px solid rgba(255, 255, 255, 0.3);
      border-radius: 50%;
      border-top-color: white;
      animation: spin 0.8s linear infinite;
      margin-right: 8px;
    }
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

// 响应式适配
@media (max-width: 576px) {
  .discount-modal {
    max-width: 100%;
    border-radius: 12px;
  }
  
  .modal-header {
    padding: 14px 16px;
    
    .modal-title {
      font-size: 16px;
    }
  }
  
  .product-info, 
  .discount-setting, 
  .commission-preview, 
  .custom-name-setting, 
  .modal-footer {
    padding: 16px;
  }
  
  .product-info {
    .product-image {
      width: 70px;
      height: 70px;
    }
  }
}
</style> 